//
//  LockQRCodeViewController.swift
//  WNLockDemo
//
//  Created by 裴威 on 31/08/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import UIKit
import SwiftyJSON
import PKHUD
import EFQRCode
import Kingfisher

class LockQRCodeViewController: UIViewController {

    @IBOutlet weak var wrapperView: UIView!
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var qrcodeWrapperView: UIView!
    
    var lock: WNLockModel?
    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavigationBarBack()
        wrapperView.layer.cornerRadius = 4
        wrapperView.layer.shadowColor = Colors(hex: 0x666666).cgColor
        wrapperView.layer.shadowOffset = CGSize(width: 0, height: 0)
        wrapperView.layer.shadowRadius = 10
        wrapperView.layer.shadowOpacity = 0.5
        fetchData()
    }
    
    private func fetchData() {
        if let id = lock?.id {
            WNLockApi.wxQrCode(lockId: id).execute { result in
                switch result {
                case .success(let json):
                    let name = json["name"].stringValue
                    let avatar = json["avatar"].stringValue
                    let qrCodeUrl = json["qrCodeUrl"].stringValue
                    self.nameLabel.text = name
                    self.avatarImageView.kf.setImage(with: URL(string: avatar))
                    if let qrCodeImage = EFQRCode.generate(content: qrCodeUrl) {
                        let imageView = UIImageView(image: UIImage(cgImage: qrCodeImage))
                        imageView.frame = self.qrcodeWrapperView.bounds
                        self.qrcodeWrapperView.addSubview(imageView)
                    }
                case .failure(let error):
                    HUD.flash(.label(error.errMsg), delay: 1.5)
                }
            }
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
